// pages/admin/timetable/timetable.js
const app = getApp();

Page({
  data: {
    classList: [{ id: 0, name: '请选择班级' }],
    classIndex: 0,
    // 学期相关数据
    semesters: [],
    semesterValues: [],
    currentSemesterIndex: 0,
    weekdays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    periods: [
      { id: 0, name: '第1节', time: '08:00-08:45' },
      { id: 1, name: '第2节', time: '08:55-09:40' },
      { id: 2, name: '第3节', time: '10:00-10:45' },
      { id: 3, name: '第4节', time: '10:55-11:40' },
      { id: 4, name: '第5节', time: '14:00-14:45' },
      { id: 5, name: '第6节', time: '14:55-15:40' },
      { id: 6, name: '第7节', time: '16:00-16:45' },
      { id: 7, name: '第8节', time: '16:55-17:40' },
      { id: 8, name: '第9节', time: '19:00-19:45' },
      { id: 9, name: '第10节', time: '19:55-20:40' }
    ],
    currentWeek: 1,
    weeks: Array.from({length: 20}, (_, i) => `第${i + 1}周`),
    maxWeeks: 20,
    timetableData: [],
    displayTimetable: Array(7).fill().map(() => Array(10).fill(null)),
    isLoading: false,
    currentDate: new Date().toISOString().split('T')[0]
  },
  
  onLoad: function() {
    // 获取班级列表
    this.fetchClassList();
    // 获取学期列表
    this.fetchSemesters();
    // 获取当前周次和学期
    this.getCurrentWeekAndSemester();
  },

  // 获取班级列表
  fetchClassList: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/admin/classes`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const classes = [{ id: 0, name: '请选择班级' }, ...res.data];
          this.setData({
            classList: classes
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取班级列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 获取学期列表
  fetchSemesters: function() {
    console.log('获取学期列表');
    wx.showLoading({
      title: '加载中...',
    });
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/admin/timetable/semesters`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('获取学期列表成功:', res.data);
        if (res.statusCode === 200) {
          const semestersData = res.data || [];
          
          if (semestersData.length > 0) {
            // 转换为前端需要的格式
            const semesterNames = semestersData.map(s => s.name);
            const semesterValues = semestersData.map(s => s.id);
            
            this.setData({
              semesters: semesterNames,
              semesterValues: semesterValues,
              currentSemesterIndex: 0
            });
          }
        } else {
          wx.showToast({
            title: res.data.message || '获取学期列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 获取当前周次和学期
  getCurrentWeekAndSemester: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/admin/timetable/current`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('获取当前周次和学期成功:', res.data);
        if (res.statusCode === 200) {
          const { currentWeek, currentSemester, maxWeeks } = res.data;
          
          // 更新周数数组
          if (maxWeeks && maxWeeks > 0) {
            this.setData({
              weeks: Array.from({length: maxWeeks}, (_, i) => `第${i + 1}周`),
              maxWeeks: maxWeeks
            });
          }
          
          // 设置当前周次
          if (currentWeek && currentWeek > 0) {
            this.setData({
              currentWeek: currentWeek
            });
          }
          
          // 设置当前学期
          if (currentSemester && this.data.semesterValues.length > 0) {
            const semesterIndex = this.data.semesterValues.findIndex(s => s === currentSemester);
            if (semesterIndex >= 0) {
              this.setData({
                currentSemesterIndex: semesterIndex
              });
            }
          }
          
          // 如果已选择班级，则获取课表数据
          if (this.data.classIndex > 0) {
            this.fetchTimetableData();
          }
        }
      },
      fail: (err) => {
        console.error('获取当前周次和学期失败:', err);
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 获取课表数据
  fetchTimetableData: function() {
    if (this.data.classIndex === 0) return;
    
    this.setData({ isLoading: true });
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const classId = this.data.classList[this.data.classIndex].id;
    const week = this.data.currentWeek;
    const semester = this.data.semesterValues[this.data.currentSemesterIndex];
    
    wx.showLoading({
      title: '加载课表...',
    });
    
    wx.request({
      url: `${serverUrl}/api/admin/timetable`,
      method: 'GET',
      data: {
        classId: classId,
        week: week,
        semester: semester
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const processedData = res.data.timetable || [];
          
          // 创建一个7x10的二维数组用于显示
          const displayTimetable = Array(7).fill().map(() => Array(10).fill(null));
          
          // 填充课程数据
          processedData.forEach(course => {
            const dayIndex = parseInt(course.day) - 1;
            const periodIndex = parseInt(course.period);
            
            if (dayIndex >= 0 && dayIndex < 7 && periodIndex >= 0 && periodIndex < 10) {
              displayTimetable[dayIndex][periodIndex] = course;
            }
          });
          
          this.setData({
            timetableData: processedData,
            displayTimetable: displayTimetable
          });
          
          console.log('处理后的课表数据:', processedData);
          console.log('显示用的课表数据:', displayTimetable);
        } else {
          wx.showToast({
            title: res.data.message || '获取课表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
        this.setData({ isLoading: false });
      }
    });
  },

  // 周次切换方法
  prevWeek: function() {
    if (this.data.currentWeek > 1) {
      this.setData({
        currentWeek: this.data.currentWeek - 1
      }, () => {
        if (this.data.classIndex > 0) {
          this.fetchTimetableData();
        }
      });
    }
  },
  
  nextWeek: function() {
    if (this.data.currentWeek < this.data.maxWeeks) {
      this.setData({
        currentWeek: this.data.currentWeek + 1
      }, () => {
        if (this.data.classIndex > 0) {
          this.fetchTimetableData();
        }
      });
    }
  },
  
  changeWeek: function(e) {
    const weekIndex = parseInt(e.detail.value);
    this.setData({
      currentWeek: weekIndex + 1
    }, () => {
      if (this.data.classIndex > 0) {
        this.fetchTimetableData();
      }
    });
  },

  // 学期切换
  changeSemester: function(e) {
    const semesterIndex = e.detail.value;
    console.log('切换学期:', this.data.semesters[semesterIndex]);
    this.setData({
      currentSemesterIndex: semesterIndex
    });
    
    // 重新获取课程表数据
    if (this.data.classIndex > 0) {
      this.fetchTimetableData();
    }
  },

  // 班级选择变化处理
  classChange: function(e) {
    console.log('班级选择变化:', e.detail.value);
    this.setData({
      classIndex: e.detail.value
    });
    
    // 重新获取课表数据
    this.fetchTimetableData();
  },

  // 在 Page 对象中添加以下方法
  
  // 显示课程详情
  showCourseDetail: function(e) {
    const { day, period } = e.currentTarget.dataset;
    console.log('点击课程:', day, period);
    
    // 获取当前单元格的课程信息
    const course = this.getCourse(day, period);
    
    if (course) {
      // 如果有课程，显示课程详情
      wx.showActionSheet({
        itemList: ['查看详情', '编辑课程', '删除课程'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 查看详情
            this.viewCourseDetail(course);
          } else if (res.tapIndex === 1) {
            // 编辑课程
            this.editCourse(course);
          } else if (res.tapIndex === 2) {
            // 删除课程
            this.deleteCourse(course);
          }
        }
      });
    } else {
      // 如果没有课程，跳转到添加课程页面
      if (this.data.classIndex === 0) {
        wx.showToast({
          title: '请先选择班级',
          icon: 'none'
        });
        return;
      }
      
      wx.navigateTo({
        url: `/pages/admin/timetable/add/add?classId=${this.data.classList[this.data.classIndex].id}&day=${day}&period=${period}&week=${this.data.currentWeek}&semester=${this.data.semesterValues[this.data.currentSemesterIndex]}`
      });
    }
  },
  
  // 获取指定位置的课程
  getCourse: function(day, period) {
    if (!this.data.displayTimetable || !this.data.displayTimetable[day]) {
      return null;
    }
    return this.data.displayTimetable[day][period];
  },
  
  // 查看课程详情
  viewCourseDetail: function(course) {
    // 跳转到课程详情页面
    wx.navigateTo({
      url: `/pages/admin/timetable/course/course?id=${course.id}&timetableId=${course.id}`
    });
  },
  
  // 编辑课程
  editCourse: function(course) {
    wx.navigateTo({
      url: `/pages/admin/timetable/edit/edit?id=${course.id}&classId=${this.data.classList[this.data.classIndex].id}&week=${this.data.currentWeek}&semester=${this.data.semesterValues[this.data.currentSemesterIndex]}`
    });
  },
  
  // 删除课程
  deleteCourse: function(course) {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除 ${course.name} 课程吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          
          const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
          
          wx.request({
            url: `${serverUrl}/api/admin/timetable/${course.id}`,
            method: 'DELETE',
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新获取课表数据
                this.fetchTimetableData();
              } else {
                wx.showToast({
                  title: res.data.message || '删除失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.error('请求失败:', err);
              wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            },
            complete: () => {
              wx.hideLoading();
            }
          });
        }
      }
    });
  },

  // 导出课表
  exportTimetable: function() {
    if (this.data.classIndex === 0) {
      wx.showToast({
        title: '请先选择班级',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '导出中...',
    });
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const classId = this.data.classList[this.data.classIndex].id;
    const week = this.data.currentWeek;
    
    // 使用微信的下载文件API
    wx.downloadFile({
      url: `${serverUrl}/api/admin/timetable/export?classId=${classId}&week=${week}`,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存文件到本地
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              wx.showToast({
                title: '导出成功',
                icon: 'success'
              });
              
              // 打开文件
              wx.openDocument({
                filePath: saveRes.savedFilePath,
                showMenu: true,
                success: function() {
                  console.log('打开文档成功');
                }
              });
            },
            fail: (err) => {
              console.error('保存文件失败:', err);
              wx.showToast({
                title: '保存文件失败',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '导出失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('下载文件失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 下载课表模板
  downloadTemplate: function() {
    if (this.data.classIndex === 0) {
      wx.showToast({
        title: '请先选择班级',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '下载模板中...',
    });
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const classId = this.data.classList[this.data.classIndex].id;
    
    wx.downloadFile({
      url: `${serverUrl}/api/admin/timetable/template/${classId}`,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存文件到本地
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              wx.showToast({
                title: '模板下载成功',
                icon: 'success'
              });
              
              // 打开文件
              wx.openDocument({
                filePath: saveRes.savedFilePath,
                showMenu: true,
                success: function() {
                  console.log('打开文档成功');
                }
              });
            },
            fail: (err) => {
              console.error('保存文件失败:', err);
              wx.showToast({
                title: '保存文件失败',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '下载模板失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('下载文件失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 导入课表
  importTimetable: function() {
    if (this.data.classIndex === 0) {
      wx.showToast({
        title: '请先选择班级',
        icon: 'none'
      });
      return;
    }
    
    // 选择文件
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['xlsx', 'xls'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].path;
        
        wx.showLoading({
          title: '解析文件中...',
        });
        
        // 上传文件
        const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
        const classId = this.data.classList[this.data.classIndex].id;
        const semester = this.data.semesterValues[this.data.currentSemesterIndex];
        
        wx.uploadFile({
          url: `${serverUrl}/api/admin/timetable/import`,
          filePath: tempFilePath,
          name: 'file',
          formData: {
            classId: classId,
            semester: semester
          },
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: (uploadRes) => {
            const result = JSON.parse(uploadRes.data);
            
            if (uploadRes.statusCode === 200) {
              wx.showToast({
                title: '导入成功',
                icon: 'success'
              });
              
              // 重新获取课表数据
              this.fetchTimetableData();
            } else {
              wx.showToast({
                title: result.message || '导入失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('上传文件失败:', err);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            });
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      }
    });
  },

  // 批量编辑课表
  batchEditTimetable: function() {
    if (this.data.classIndex === 0) {
      wx.showToast({
        title: '请先选择班级',
        icon: 'none'
      });
      return;
    }
    
    wx.showActionSheet({
      itemList: ['下载课表模板', '导入课表', '导出当前课表'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 下载模板
          this.downloadTemplate();
        } else if (res.tapIndex === 1) {
          // 导入课表
          this.importTimetable();
        } else if (res.tapIndex === 2) {
          // 导出课表
          this.exportTimetable();
        }
      }
    });
  },
  
  // 导航到编辑课表页面
  navigateToEdit: function() {
    const classId = this.data.classList[this.data.classIndex].id;
    const week = this.data.currentWeek;
    const semester = this.data.semesterValues[this.data.currentSemesterIndex];
    
    wx.navigateTo({
      url: `/pages/admin/timetable/edit/edit?classId=${classId}&week=${week}&semester=${semester}`
    });
  },

  // 导航到导入课表页面
  navigateToImport: function() {
    wx.navigateTo({
      url: '/pages/admin/timetable/import/import'
    });
  }
});


